package com.dailywork.basepro.thread;

import net.jcip.annotations.GuardedBy;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * 线程的取消和关闭
 *
 * @author think
 * @version 1.0.0
 * @since 2020/4/26
 */
public class CancelVolatile implements Runnable {

    private final List<BigInteger> pri = new ArrayList<BigInteger>();

    private volatile boolean cancelled;

    @Override
    public void run() {
        BigInteger p = BigInteger.ONE;
        while (!cancelled) {
            p = p.nextProbablePrime();
            synchronized (this) {
                pri.add(p);
            }
        }
    }

    private void cancel() {
        cancelled = true;
    }

    @GuardedBy("this")
    private List<BigInteger> get() {
        return new ArrayList<>(pri);
    }

    public static void main(String[] args) {
        CancelVolatile cancelVolatile = new CancelVolatile();
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(cancelVolatile);
        try {
            SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            cancelVolatile.cancel();
        }
        System.out.println(cancelVolatile.get());
    }
}